package controller

import (
	"github.com/doujunyu/gogo/gogo_log"
	"github.com/doujunyu/gogo/job"
	"github.com/doujunyu/gogo/sql_aid"
	"go_self/model"
	"go_self/server"
	"strconv"
)

// UserAddressByList 收货地址列表
func UserAddressByList(j *job.Job) {

	userAddressSql, arge := sql_aid.PgTable(model.TableByUserAddress).Where("user_id = ?", j.GroupData["user_id"]).OrderBy("is_default desc,time_u desc").ToSql()
	userAddress, err := sql_aid.DataToMap(model.PgSql.Query(userAddressSql, arge...))
	if err != nil {
		j.JsonSuccess()
		return
	}
	if len(userAddress) == 0 {
		j.JsonSuccess()
		return
	}
	j.JsonSuccess(userAddress)
	return
}

// UserAddressByAdd 收货地址添加
func UserAddressByAdd(j *job.Job) {
	input := make(map[string]string)
	input["name"] = j.Input["name"]
	input["mobile"] = j.Input["mobile"]
	input["address"] = j.Input["address"]
	input["address_code"] = j.Input["address_code"]
	input["address_info"] = j.Input["address_info"]
	input["is_default"] = j.Input["is_default"]
	err := server.UserAddressByAdd(j.GroupData["user_id"].(int64), input)
	if err != nil {
		j.JsonError(nil, err.Error())
		return
	}
	j.JsonSuccess()
	return
}

// UserAddressByEdit 收货地址编辑
func UserAddressByEdit(j *job.Job) {
	input := make(map[string]string)
	input["id"] = j.Input["id"]
	input["name"] = j.Input["name"]
	input["mobile"] = j.Input["mobile"]
	input["address"] = j.Input["address"]
	input["address_code"] = j.Input["address_code"]
	input["address_info"] = j.Input["address_info"]
	input["is_default"] = j.Input["is_default"]
	err := server.UserAddressByEdit(j.GroupData["user_id"].(int64), input)
	if err != nil {
		j.JsonError(nil, err.Error())
		return
	}
	j.JsonSuccess()
	return
}

// UserAddressByEditIsDefault 收货地址默认值更改
func UserAddressByEditIsDefault(j *job.Job) {
	if j.Input["user_address_default_id"] == "" {
		j.JsonError(nil, "缺少参数")
		return
	}
	def, _ := strconv.ParseInt(j.Input["user_address_default_id"], 10, 64)

	err := server.UserAddressByEditIsDefault(j.GroupData["user_id"].(int64), def)
	if err != nil {
		gogo_log.Error("controller_UserAddressByEditIsDefault", "收货地址默认值更改", err.Error())
		j.JsonError(nil, "更新失败")
		return
	}
	j.JsonSuccess()
	return
}

// UserAddressByDel 删除收货地址
func UserAddressByDel(j *job.Job) {
	if j.Input["user_address_ids"] == "" {
		j.JsonError(nil, "缺少参数")
		return
	}
	err := server.UserAddressByDel(j.GroupData["user_id"].(int64), j.Input["user_address_ids"])
	if err != nil {
		j.JsonError(nil, err.Error())
		return
	}
	j.JsonSuccess()
	return
}
